package org.wangliang181230.leetcode.problems.p_1117;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

/**
 * @author wangliang181230
 */
public class H2O_1117 {

	private Semaphore hSema = new Semaphore(2);
	private Semaphore oSema = new Semaphore(1);
	private CyclicBarrier cb = new CyclicBarrier(3);


	public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
		hSema.acquire();
		releaseHydrogen.run();
		this.await();
		hSema.release();
	}

	public void oxygen(Runnable releaseOxygen) throws InterruptedException {
		oSema.acquire();
		releaseOxygen.run();
		this.await();
		oSema.release();
	}

	private void await() throws InterruptedException {
		try {
			this.cb.await();
		} catch (BrokenBarrierException e) {
		}
	}
}
